//
//  ResourceLoaderOldSupport.m
//  AppleCilent
//
//  Created by Nail Sharipov on 02/04/14.
//  Copyright (c) 2014 Nail Sharipov. All rights reserved.
//

#import "ResourceData.h"
#import "MainProperties.h"
#import "DataRequest.h"

@implementation ResourceData
{
    MainProperties* properties;
    NSObject<IResorceLoaded>* listener;

    NSMutableArray* fileList;
    NSString* imageFolderPath;
    BOOL isMenuLoaded;
    BOOL isGoodsLoaded;
    BOOL isImagesLoaded;
    
    float percentStep;
    float percent;
}

+ (ResourceData*)getInstance
{
    static ResourceData* instance;
    
    @synchronized(self)
    {
        if (!instance)
            instance = [[ResourceData alloc] init];
        return instance;
    }
}

- (id)init
{
    self = [super init];
    isMenuLoaded = NO;
    isGoodsLoaded = NO;
    isImagesLoaded = NO;
    properties = [MainProperties getInstance];
    
    imageFolderPath = [properties getImageFolder];
    NSLog(@"imahe path: %@", imageFolderPath);
    
    percent = 0.0f;
    
    return self;
}

-(void)setListener:(NSObject<IResorceLoaded>*) object
{
    listener = object;
}

-(BOOL)isLoaded
{
    return isMenuLoaded && isGoodsLoaded && isImagesLoaded;
}

-(void)load {
    isMenuLoaded = NO;
    isGoodsLoaded = YES;
    isImagesLoaded = NO;
    
    NSString* rootUrl = [properties getRootUrl];
    
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat: @"%@getPriceData", rootUrl]];
    DataRequest* request = [[DataRequest alloc] init];
    [request getURL:url onReady:^(NSMutableData* data)
     {
         [self menuListLoaded: data];
     }];
    

    url = [NSURL URLWithString:[NSString stringWithFormat: @"%@getPictureFileList", rootUrl]];
    request = [[DataRequest alloc] init];
    [request getURL:url onReady:^(NSMutableData* data)
     {
         [self fileListLoaded: data];
     }];

}

-(void)menuListLoaded: (NSMutableData*) data
{
    percent = percent + 0.05f;
    [listener onLoadProgress:percent];
    NSLog(@"menuListLoaded response");
    NSError *parseError = nil;
    NSArray* arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&parseError];
    
    NSMutableArray* menuListQueue = [[NSMutableArray alloc] init];
 
    for (NSDictionary* menuData in arr)
    {
        MenuDomain* menu = [[MenuDomain alloc] init: menuData];
        [menuListQueue addObject:menu];
    }
    
    self.menuList = [[NSArray alloc] initWithArray:menuListQueue];

    isMenuLoaded = YES;
    [self loadCompleted];
    
}

-(NSArray*)getLocalFileList
{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSError* error;
    NSArray* files = [fileManager contentsOfDirectoryAtPath:imageFolderPath error:&error];
    return files;
}


-(void)fileListLoaded: (NSMutableData *) data
{
    NSLog(@"fileListLoaded response");
    percent = percent + 0.05f;
    [listener onLoadProgress:percent];
    NSError *parseError = nil;
    NSArray* arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&parseError];
    fileList = [[NSMutableArray alloc] initWithArray: arr];

    // check that may be some files are already presented
//    NSLog(@"check that may be some files are already presented");
    NSArray* localFiles = [self getLocalFileList];
    if (localFiles != nil)
    {
        for (NSString* localFile in localFiles)
        {
//            NSLog(@"check file: %@", localFile);
            if ([fileList containsObject:localFile])
            {
//                NSLog(@"file is exist: %@", localFile);
                [fileList removeObject:localFile];
            }
        }
    }
    
    if (parseError != nil)
    {
        NSLog(@"parse error: %@", parseError);
    }
    
    int n = [fileList count];
    
    if (n > 0) {
        percentStep = 0.9f / (float)n;
    } else {
        percentStep = 0.9f;
    }
    
    [self loadNextFile];
}


-(void)loadNextFile
{
    if ([fileList count] > 0)
    {
        NSString* fileName = [fileList firstObject];
        [fileList removeObjectAtIndex:0];
        NSURL* url = [NSURL URLWithString:[NSString stringWithFormat: @"%@getImage?name=%@&mobile=false", [properties getRootUrl], fileName]];
        
        DataRequest* dataRequest = [[DataRequest alloc] init];
        [dataRequest downloadURL:url fileName:fileName folder:imageFolderPath onReady:^(NSString* filePath)
        {
            [self fileLoaded: filePath];
        }];
    }
    else
    {
        isImagesLoaded = YES;
        [self loadCompleted];
    }
}

-(void)fileLoaded:(NSString*)filePath
{
    percent = percent + percentStep;
    [listener onLoadProgress:percent];
    [self loadNextFile];
}

-(void)loadCompleted
{
    if ([self isLoaded]) {
        [listener onLoaded];
        [listener onLoadProgress:1.0f];
    }
}

-(MenuDomain*)getMenuById: (NSInteger) menuId
{
    for (MenuDomain* menu in self.menuList) {
        if ([menu getId] == menuId) {
            return menu;
        }
    }
    return nil;
}

@end
